package com.vonchange.purchase.purchase.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.jxls.exception.ParsePropertyException;
import net.sf.jxls.transformer.XLSTransformer;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.vonchange.headb.core.map.HeaMap;
import com.vonchange.purchase.deed.bean.Deed;
import com.vonchange.purchase.deed.service.IDeedService;
import com.vonchange.purchase.good.bean.Good;
import com.vonchange.purchase.good.service.IGoodService;
import com.vonchange.purchase.merchant.service.IMerchantService;
import com.vonchange.purchase.purchase.bean.Purchase;
import com.vonchange.purchase.purchase.dao.IPurchaseDao;
import com.vonchange.purchase.purchase.service.IPurchaseService;
import com.vonchange.utils.crud.dao.IBaseDao;
import com.vonchange.utils.crud.service.normal.impl.BaseServiceImpl;
import com.vonchange.utils.date.DateUtil;
import com.vonchange.utils.excel.PoiUtil;
import com.vonchange.utils.file.FileUtils;
import com.vonchange.utils.map.MyHashMap;
import com.vonchange.utils.string.StringUtil;
import com.vonchange.utils.web.RequestUtils;
import com.vonchange.utils.web.Result;

@Service
@Transactional
public class PurchaseServiceImpl extends BaseServiceImpl<Purchase> implements IPurchaseService {
	@Resource
	private IPurchaseDao purchaseDao;
	@Resource
	private IGoodService goodService;
	@Resource
	private IMerchantService merchantService;
	@Resource
	private IDeedService deedService;

	@Override
	public IBaseDao<Purchase> getDao() {
		// TODO Auto-generated method stub
		return purchaseDao;
	}

	public void initSave(Purchase entity) {
		entity.setCreateTime(new Date());
	}

	public void initUpdate(Purchase entity) {
		entity.setUpdateTime(new Date());
	}

	public void initFind(HeaMap parameter) {
		if (null == parameter.get("isDelete_eq")) {
			parameter.set("isDelete_eq", 0);
		}
	}

	public void exportOne(String deedId, Purchase parentMerchant) throws IOException {
		if(null==parentMerchant){
			parentMerchant=new Purchase();
			parentMerchant.setParentMerchantName("");
		}
		String parentMerchantId=parentMerchant.getParentMerchantId();
		List<Purchase> purchaseList = findList(new HeaMap().setAddSelect("sum_number").set("deedId_eq", deedId).set("parentMerchantId_eq", parentMerchantId).setAddGroup("goodId"));
		List<Purchase> merchantList = findList(new HeaMap().setAddSelect("sum_number").set("deedId_eq", deedId).set("parentMerchantId_eq", parentMerchantId).setAddGroup("merchantId"));
		List<Purchase> merchantGoodList = null;
		Map<String, Float> map = new HashMap<String, Float>();
		Map<String, String> remarkMap = new HashMap<String, String>();
		for (Purchase merchant : merchantList) {
			merchantGoodList = findList(new HeaMap().setAddSelect("sum_number").set("deedId_eq", deedId).set("merchantId_eq", merchant.getMerchantId()).setAddGroup("goodId"));
			for (Purchase purchase : merchantGoodList) {
				map.put(purchase.getMerchantId() + purchase.getGoodId(), purchase.getNumber());
				remarkMap.put(purchase.getMerchantId() + purchase.getGoodId(), purchase.getRemark());
			}
		}
		List<Map<String, Object>> numberList = null;
		for (Purchase purchase : purchaseList) {
			numberList = new ArrayList<Map<String, Object>>();
			Float number = new Float(0);
			for (Purchase merchant : merchantList) {
				number = map.get(merchant.getMerchantId() + purchase.getGoodId());
				if (null == number) {
					number = 0f;
				}
				if(number==0){
					number=null;
				}
				String remark = remarkMap.get(merchant.getMerchantId() + purchase.getGoodId());
				numberList.add(new MyHashMap().set("number", number).set("remark", remark));
			}
			purchase.setNumberList(numberList);
		}
		Map<String, Object> beans = new HashMap<String, Object>();
		beans.put("purchaseList", purchaseList);
		beans.put("merchantList", merchantList);
		beans.put("name", parentMerchant.getParentMerchantName());
		XLSTransformer transformer = new XLSTransformer();
		if (null == parentMerchantId) {
			transformer.setColumnPropertyNamesToHide(new String[] { "number.remark" });
		}
		String tplXls = "tpl.xls";
		try {
			if (null == parentMerchantId) {
				parentMerchantId = "";
				tplXls = "tplq.xls";
			}
			transformer.transformXLS(resPath+"/xls/tpl/" + tplXls, beans, StringUtil.format(resPath+"/xls/gen/"+"{0}{1}.xls", deedId, parentMerchantId));
		} catch (ParsePropertyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 菜价

	}
   private String resPath=null;
	@Override
	public Result export(String deedId) {
		List<Purchase> pmList = findList(new HeaMap().setAddSelect("parent_merchant").set("deedId_eq", deedId).setAddGroup("parentMerchantId"));
		if(null==pmList||pmList.isEmpty()){
			return new Result().setStatusFail().setMsg("没有要导出的数据！");
		}
		resPath=RequestUtils.getWebRealPath("/res/");
		System.out.println(resPath);
		try {
			exportOne(deedId, null);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		for (Purchase purchase : pmList) {
			try {
				exportOne(deedId, purchase);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		Map<String, Object> beans = new HashMap<String, Object>();
		List<Good> goodList = goodService.findList(null);
		beans.put("pageQ", goodList);
		XLSTransformer transformer = new XLSTransformer();
		try {
			transformer.transformXLS(resPath+"/xls/tpl/" +"tplgood.xls", beans, StringUtil.format(resPath+"/xls/gen/" +"{0}good.xls", deedId));
		} catch (ParsePropertyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String resultPath="";
		try {
		     resultPath=	copyToOne(deedId,pmList);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new Result().setResult(resultPath);
	}
	private String copyToOne(String deedId,List<Purchase> pmList) throws IOException {
		String path=resPath+"/xls/gen/"+deedId+".xls";
		FileInputStream file = new FileInputStream(path);
		POIFSFileSystem ts = new POIFSFileSystem(file);
		HSSFWorkbook wb = new HSSFWorkbook(ts);
		HSSFWorkbook wbx = null;
		String pathx=resPath+"/xls/gen/"+deedId;
		HSSFSheet sheetx=null;
		HSSFSheet sheetNew=null;
	    for (Purchase purchase : pmList) {
			 wbx = new HSSFWorkbook(new POIFSFileSystem(new FileInputStream(pathx+purchase.getParentMerchantId()+".xls")));
			 sheetx=	 wbx.getSheetAt(0);
			 sheetNew=wb.createSheet(purchase.getParentMerchantName());
             try {
				PoiUtil.copySheet(sheetNew, sheetx, wb, wbx);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}             
		}	
	    wbx = new HSSFWorkbook(new POIFSFileSystem(new FileInputStream(pathx+"good.xls")));
		 sheetx=	 wbx.getSheetAt(0);
		 sheetNew=wb.createSheet("配送报价单");
	    try {
			PoiUtil.copySheet(sheetNew, sheetx, wb, wbx);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	     Deed deed=  deedService.findById(deedId);
		wb.write(FileUtils.openOutputStream(new File(resPath+"/xls/gen/"+DateUtil.format("yyyy-MM-dd-",deed.getCreateTime())+deed.getId()+".xls")));
		return "res/xls/gen/"+DateUtil.format("yyyy-MM-dd-",deed.getCreateTime())+deed.getId()+".xls";
	}
	/*
	 * @Override public Result export(String deedId) throws IOException {
	 * List<Purchase> purchaseList= findList(new
	 * HeaMap().setAddSelect("sum_number").set("deedId_eq",
	 * deedId).setAddGroup("goodId")); List<Purchase> merchantList= findList(new
	 * HeaMap().setAddSelect("sum_number").set("deedId_eq",
	 * deedId).setAddGroup("merchantId")); List<Purchase> merchantGoodList=null;
	 * Map<String, Float> map=new HashMap<String, Float>(); Map<String, String>
	 * remarkMap=new HashMap<String, String>(); for (Purchase merchant :
	 * merchantList) { merchantGoodList= findList(new
	 * HeaMap().setAddSelect("sum_number").set("deedId_eq", deedId)
	 * .set("merchantId", merchant.getMerchantId()).setAddGroup("goodId")); for
	 * (Purchase purchase : merchantGoodList) {
	 * map.put(purchase.getMerchantId()+purchase.getGoodId(),
	 * purchase.getNumber());
	 * remarkMap.put(purchase.getMerchantId()+purchase.getGoodId(),
	 * purchase.getRemark()); } } List<Map<String, Object>> numberList=null; for
	 * (Purchase purchase : purchaseList) { numberList=new ArrayList<Map<String,
	 * Object>>(); Float number=new Float(0); for (Purchase merchant :
	 * merchantList) {
	 * number=map.get(merchant.getMerchantId()+purchase.getGoodId());
	 * if(null==number){ number=0f; } String
	 * remark=remarkMap.get(merchant.getMerchantId()+purchase.getGoodId());
	 * numberList.add(new MyHashMap().set("number", number).set("remark",
	 * remark)); } purchase.setNumberList(numberList); } Map<String,Object>
	 * beans = new HashMap<String,Object>(); beans.put("purchaseList",
	 * purchaseList); beans.put("merchantList", merchantList); //菜价 List<Good>
	 * goodList=goodService.findList(null); beans.put("pageQ", goodList);
	 * XLSTransformer transformer = new XLSTransformer(); //
	 * transformer.setColumnPropertyNamesToHide( new String[]{"number.remark"}
	 * ); String a=null; try { long time=new Date().getTime(); a= new
	 * Long(time).toString(); transformer.transformXLS("E://test/tpl.xls",
	 * beans, "E://test/"+a+".xls"); } catch (ParsePropertyException e) { //
	 * TODO Auto-generated catch block e.printStackTrace(); } catch
	 * (InvalidFormatException e) { // TODO Auto-generated catch block
	 * e.printStackTrace(); } //copySheet return null; }
	 */
}